package de.szut.traineeslife.taks;

import java.util.ArrayList;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ListView;

import com.google.api.services.drive.Drive;
import com.google.api.services.drive.model.File;

import de.szut.traineeslife.adapter.FilesFromDriveAdapter;
import de.szut.traineeslife.utils.DriveHelper;

public class FilesInDriveTask extends AsyncTask<Void, Void, Void> {

	private ProgressDialog dialog;
	private Context mContext;
	private ArrayList<File> mFileList;
	private Drive mService;
	private FilesFromDriveAdapter mAdapter;
	private ListView mListview;
	DriveHelper mDriveHelper;

	/**Displays all Files from Drive
	 * @param context
	 * @param fileList
	 * @param service
	 * @param adapter
	 * @param listview
	 * @param driveHelper
	 */
	public FilesInDriveTask(Context context, ArrayList<File> fileList, Drive service, FilesFromDriveAdapter adapter, ListView listview, DriveHelper driveHelper) {
		mContext = context;
		mFileList = fileList;
		mService = service;
		mAdapter = adapter;
		mListview = listview;
		mDriveHelper = driveHelper;
	}

	@Override
	protected Void doInBackground(Void... params) {
		try {
			ArrayList<File> files = mDriveHelper.getModelFromDrive(mService);
			for (File file : files) {
				mFileList.add(file);
				Log.d("DONWLOADTASK", file.getTitle());
				Log.d("DONWLOADTASK", file.getId());
				Log.d("DONWLOADTASK", file.getAlternateLink());
				if (file.getDownloadUrl() != null && file.getDownloadUrl().length() > 0) {
					Log.d("URL", "FJEDEN");
				}
			}
			Thread.sleep(5000);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	protected void onPostExecute(Void result) {
		super.onPostExecute(result);
		mAdapter = new FilesFromDriveAdapter(mContext, 0, mFileList);
		mAdapter.notifyDataSetChanged();
		mListview.setAdapter(mAdapter);
		if (dialog != null) {
			dialog.dismiss();
		}
	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		dialog = new ProgressDialog(mContext);
		dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		dialog.setMessage("Lädt Dokumente von Drive....");
		dialog.setCancelable(false);
		dialog.show();
	}
}
